from http.cookiejar import Cookie
from flask import Blueprint, request, jsonify
from flask_login import login_required
from flask_login import current_user
from extensions import db,i_maotai_rob
from sqlalchemy import text
import requests
from datetime import datetime

api_bp = Blueprint('api', __name__)


def get_location_by_ip(ip):
    AMAP_API_KEY = 'f82a27c626f7ba4e865da3799f1a722f'
    url = f"https://restapi.amap.com/v3/ip?ip={ip}&key={AMAP_API_KEY}"
    try:
        response = requests.get(url)
        data = response.json()
        print(data)
        if data['status'] == '1':  # 请求成功
            province = data.get('province', '未知')
            city = data.get('city', '未知')
            location = data.get('rectangle', '').split(';')[0]  # 经纬度范围
            longitude, latitude = location.split(',') if location else ('未知', '未知')
            return {
                'province': province,
                'city': city,
                'longitude': longitude,
                'latitude': latitude
            }
        
        else:
            # {'error': '无法获取位置信息'}
            return {
                'province': None,
                'city': None,
                'longitude': None,
                'latitude': None,
                'error': '无法获取位置信息'
            }
    except Exception as e:
        # {'error': str(e)}
        return {
                'province': None,
                'city': None,
                'longitude': None,
                'latitude': None,
                'error': str(e)
            }

def get_client_ip():
    # 优先从代理头获取（如 Nginx 配置了 X-Forwarded-For）
    if request.headers.getlist("X-Forwarded-For"):
        ip = request.headers.getlist("X-Forwarded-For")[0].split(",")[0]
    else:
        ip = request.remote_addr  # 直接连接的客户端 IP
    return ip


@api_bp.route('/imaotai/users/add',methods=['POST'])
@login_required # 确保用户已登录
def users_add():
    users_id = current_user.id
    # 获取 用户请求ip
    client_ip = get_client_ip()

    # 根据ip获取位置
    location_by_ip = get_location_by_ip(client_ip)
    province = location_by_ip['province']
    city = location_by_ip['city']
    lng = location_by_ip['longitude']
    lat = location_by_ip['latitude']

    # 获取前端的值
    form_data = request.form.to_dict()
    mobile = form_data['mobile']
    email = form_data['email']
    appointmentMode = form_data['appointmentMode']
    # 获取所有名为 'products' 的表单字段的值
    products = request.form.getlist('products')
    products = ','.join(products)
    # 获取设备id
    device_id = i_maotai_rob.get_device_id()

    sql = f"""
            INSERT INTO imaotai_user 
                (mobile, email,device_id,products,client_ip,province_name,city_name,lat,lng,appointmentMode,users_id) 
            VALUES ('{mobile}','{email}','{device_id}','{products}','{client_ip}','{province}','{city}','{lat}','{lng}','{appointmentMode}',{users_id});
        """
    db.session.execute(text(sql))
    db.session.commit()

    response = {
        "code":200,
        "success": True,
        "message": "执行成功"
    }
    return jsonify(response)

@api_bp.route('imaotai/users/update',methods=['POST'])
@login_required
def users_update():
    # 获取前端的值
    form_data = request.form.to_dict()
    # 获取所有名为 'products' 的表单字段的值
    products = request.form.getlist('products')
    products = ','.join(products)
    sql = f"""
            UPDATE 
                imaotai_user
            SET  
                email = '{form_data["email"]}', 
                products = '{products}', 
                province_name = '{form_data["province"]}',
                city_name = '{form_data["city"]}', 
                lat = '{form_data["lat"]}', 
                lng = '{form_data["lng"]}', 
                appointmentMode = '{form_data["appointmentMode"]}' 
            WHERE 
                id = {form_data["id"]};

        """
    db.session.execute(text(sql))
    db.session.commit()
    return {"code":200,"success": True,"message": "修改成功"}


@api_bp.route('/imaotai/users/login',methods=['POST'])
def imaotai_users_login():
    form_data = request.form.to_dict()
    id = form_data['user_id']
    mobile = form_data['mobile']
    device_id = form_data['device_id']
    code =  form_data['code']

    if not code:
        return {"code":300,"success": False,"message": "验证码不能为空"}

    # 登录
    filtered = i_maotai_rob.login(mobile, code, device_id)

    if filtered:
        if filtered['code'] == 2000:
            filtered_data = filtered['data']

            userId = filtered_data.get('userId')
            userName = filtered_data.get('userName')
            mobile = filtered_data.get('mobile')
            token = filtered_data.get('token')
            cookie = filtered_data.get('cookie')
            did = filtered_data.get('did')
            verifyStatus = filtered_data.get('verifyStatus')

            # 获取token过期时间
            token_expire_time = i_maotai_rob.check_jwt(token)
            cookie_expire_time = i_maotai_rob.check_jwt(cookie)

            sql =f'''
                    UPDATE 
                        imaotai_user
                    SET 
                        imaotai_user_id = '{userId}', 
                        imaotai_user_name = '{userName}', 
                        status = 1, 
                        token = '{token}',
                        cookie = '{cookie}', 
                        did = '{did}', 
                        verifyStatus = {verifyStatus},
                        token_expire_time = '{token_expire_time}', 
                        cookie_expire_time = '{cookie_expire_time}'
                    WHERE 
                        id = {id};
                '''
            db.session.execute(text(sql))
            db.session.commit()
            return {"code":200,"success": True,"message": "登录成功"}
        
        else:
            return {"code":401,"success": False,"message":filtered['message']}
    return {"code":300,"success": False,"message": "登录异常"}
    


@api_bp.route('/imaotai/users/code', methods=['POST'])
def imaotai_users_code():
    # 获取表单数据
    form_data = request.form.to_dict()
    device_id = form_data['device_id']
    mobile = form_data['mobile']

    # 发送验证码
    message = i_maotai_rob.send_code(mobile,device_id)
    return {"code":200,"success": True, "message": message}


@api_bp.route("/imaotai/users/delete",methods=['POST'])
def imaotai_users_delete():
    user_id = request.form.get('id')
    sql = f"""
            DELETE 
            FROM 
                imaotai_user
            WHERE 
                id={user_id};
        """

    db.session.execute(text(sql))
    db.session.commit()
    return {"code":200,"success": True, "message": "操作成功"}

@api_bp.route("/imaotai/products", methods=['POST'])
def imaotai_products():
    formatted_date = datetime.now().strftime("%Y-%m-%d") 
    sql = f"""
        SELECT 
            * 
        FROM 
            products
        WHERE 
            created_date = '{formatted_date}';
    """
    result = db.session.execute(text(sql))
    products = [dict(row._mapping) for row in result]
    if products:

        return {"code":200,"success": True,"message": "商品列表数据获取成功","data":products}
    
    return {"code":300,"success": False,"message": "商品列表数据获取失败","data":products}

